package com.agrm.rabc.service.impl;


import com.agrm.model.rabc.dto.GroupRoleMapping;
import com.agrm.rabc.mapper.GroupRoleMappingDao;
import com.agrm.rabc.service.GroupRoleMappingService;
import com.agrm.rabc.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;

@CacheConfig(cacheNames = "c.s.r.s.impl.GroupRoleServiceImpl")
@Service
public class GroupRoleServiceImpl implements GroupRoleMappingService {
    private GroupRoleMappingDao groupRoleMappingDao;
    private RoleService roleService;

    @Autowired
    public void setGroupRoleMappingDao(GroupRoleMappingDao groupRoleMappingDao) {
        this.groupRoleMappingDao = groupRoleMappingDao;
    }

    @Autowired
    public void setRoleService(RoleService roleService) {
        this.roleService = roleService;
    }

    @Cacheable(keyGenerator = "customKeyGenerator")
    @Override
    public List<GroupRoleMapping> findAll(GroupRoleMapping grm) {
        List<GroupRoleMapping> mappings = groupRoleMappingDao.findAll(grm);
        mappings.forEach(it -> {
            it.setRole(this.roleService.findById(it.getRoleId()));
        });
        return mappings;
    }

    @Cacheable(key = "#p0")
    @Override
    public GroupRoleMapping findById(Integer id) {
        GroupRoleMapping mapping = groupRoleMappingDao.selectById(id);
        mapping.setRole(this.roleService.findById(mapping.getRoleId()));
        return mapping;
    }

    @CacheEvict(allEntries = true)
    @Override
    public boolean save(GroupRoleMapping grm) {
        return groupRoleMappingDao.insert(grm) > 0;
    }

    @CacheEvict(allEntries = true)
    @Override
    public boolean update(GroupRoleMapping grm) {
        return groupRoleMappingDao.updateById(grm) > 0;
    }

    @CacheEvict(allEntries = true)
    @Override
    public int deleteByIds(List<Integer> ids) {
        return groupRoleMappingDao.deleteByIds(ids);
    }
}
